import datetime
import logging
import time
import urllib
from urllib import request, parse
import ssl
import json
import playsound

logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
f_handler = logging.FileHandler('trace1.log')
f_handler.setLevel(logging.INFO)
f_handler.setFormatter(logging.Formatter("%(asctime)s - %(levelname)s - %(filename)s[:%(lineno)d] - %(message)s"))
logger.addHandler(f_handler)

# context = ssl._create_unverified_context()

url = "https://maicai.api.ddxq.mobi/homeApi/categoriesNewDetail"

uid = "6254e70eadeb2f0001f9e65f"  # 用户号，从Fiddler中抓取
station_id = "6108f66781ff030001369967"  # 站点好，小程序首页中选中自家地址后，再从Fiddler抓取
cookie = "DDXQSESSID=c11415dee8cd932642f474023ff686c5"  # 登录后，从Fiddler抓取
category_id_map = {
    "category_id_rouqindan": "5fb5644d8858c1fb7f61a666",  # 肉禽蛋
    "category_id_shucai": "5fb5644c8858c1fb7f61a660",  # 蔬菜豆制品
    "category_id_shuiguo": "5fb5644d8858c1fb7f61a664",  # 水果鲜花
}
category_id = category_id_map["category_id_shucai"]
print("testing alert sound...")
playsound.playsound("alert3.mp3")
print("done")

getDict = {
    "uid": uid,
    "longitude": "121.425446",
    "latitude": "31.237419",
    "station_id": station_id,
    "city_number": "0101",
    "api_version": "9.49.2",
    "app_version": "2.82.0",
    "applet_source": "",
    "channel": "applet",
    "app_client_id": "4",
    "sharer_uid": "",
    "s_id": "c11415dee8cd932642f474023ff686c5",
    "openid": "osP8I0WwHO78fDdWv6vaJWMVXZFg",
    "h5_source": "",
    "device_token": "WHJMrwNw1k/FKPjcOOgRd+J1ee6rW3n/PRrH6Kq8m9g66TlQ+UvE66AmDe51vPg9Mc/XtPI0QeUz7MbJchBByraRk0jv7nINFdCW1tldyDzmauSxIJm5Txg==1487582755342",
    "category_id": category_id,
    "version_control": "new",
    "nars": "65417311d4a4bf966e8fc65ebc18fa04",
    "sesi": "DPS3Eoh36568f2d419bc4975e324c4be92cfd12"
}
headers = {
    "Host": "maicai.api.ddxq.mobi",
    "content-type": "application/x-www-form-urlencoded",
    "Connection": "keep-alive",
    "User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36 MicroMessenger/7.0.9.501 NetType/WIFI MiniProgramEnv/Windows WindowsWechat",
    "ddmc-api-version": "9.49.2",
    "ddmc-app-client-id": "4",
    "ddmc-build-version": "2.82.0",
    "ddmc-channel": "applet",
    "ddmc-city-number": "0101",
    "ddmc-device-id": "osP8I0WwHO78fDdWv6vaJWMVXZFg",
    "ddmc-ip": "",
    "ddmc-latitude": "31.237419",
    "ddmc-longitude": "121.425446",
    "ddmc-os-version": "[object Undefined]",
    "ddmc-station-id": station_id,
    "ddmc-uid": uid,
    "Referer": "https://servicewechat.com/wx1e113254eda17715/422/page-frame.html",
    # "Accept-Encoding": "gzip, deflate, br",
    "Cookie": cookie
}

from urllib.parse import urlencode

url_params = urlencode(getDict)
url = f"{url}?{url_params}"
request = urllib.request.Request(url=url, headers=headers)

while True:
    now = datetime.datetime.now()
    now_time = datetime.datetime.strptime(now.strftime('%H:%M:%S'), '%H:%M:%S')
    open_time = datetime.datetime.strptime('6:20:00', '%H:%M:%S')
    close_time = datetime.datetime.strptime('22:00:00', '%H:%M:%S')
    if open_time < now_time < close_time:
        try:
            response = urllib.request.urlopen(request)
            json_resp = json.loads(response.read().decode("utf-8"))
            logger.info(json_resp)
            if "success" in json_resp and json_resp["success"]:
                product_list = json_resp["data"]["products"]
                first_product = product_list[0] if len(product_list) > 0 else None
                if first_product:
                    is_stockout_notify = first_product["is_stockout_notify"]
                    if is_stockout_notify == 0:  # -1 表示有货, 0 表示无货
                        print("x", end="", flush=True)
                    else:
                        print(f"\n{now.strftime('%Y-%m-%d %H:%M:%S')} 有货物上架啦！！！冲鸭！！！")
                        playsound.playsound("alert2.mp3")
            else:
                print(f"code={json_resp['code']}, msg={json_resp['msg']}")
            # assert len(data_list) is not None
            # data = data_list[0]
            # if "closed" in data and data["closed"]:
            #     print("今日已打烊，请明日再来吧~")
            # else:
            #     date_list = data["time"]
            #     assert len(date_list) > 0
            #     date = date_list[0]
            #     time_list = date["times"]
            #     assert len(time_list) > 0
            #     first_time = time_list[0]
            #     if first_time["fullFlag"]:
            #         print("k", end="", flush=True)
            #     else:
            #         print("有运力拉！！！冲鸭！！！")
            #         playsound.playsound("alert1.mp3")
            #         print(date_list)
            #         print(time_list)
        except Exception as ex:
            print("error found...")
            print(ex)
            logger.error(ex)
        time.sleep(30)
    else:
        print(".", end="", flush=True)
        time.sleep(1)
